package com.c3w.synchro.administration.clubAdministration;

import com.c3w.synchro.administration.service.ClubAdministrationService;
import com.c3w.synchro.exporter.ExcelBeanConverterEngine;
import com.c3w.synchro.member.bean.Athlete;
import com.c3w.synchro.member.bean.Club;
import com.c3w.synchro.member.bean.Team;
import com.c3w.synchro.member.bean.TeamType;
import com.c3w.synchro.member.service.AthleteService;
import com.c3w.synchro.member.service.ClubService;
import com.c3w.synchro.member.service.TeamService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Collection;


/**
 * User: magirard
 * Date: 13-02-09
 */
@Service("clubAdministrationService")
public class ClubAdministrationServiceImpl implements ClubAdministrationService {
    private static final Logger LOGGER = Logger.getLogger(ClubAdministrationServiceImpl.class);

    @Autowired
    ExcelBeanConverterEngine excelBeanConverterEngine;

    @Autowired
    AthleteService athleteService;

    @Autowired
    ClubService clubService;

    @Autowired
    TeamService teamService;

    @Override
    public void importExcelSheet(String filePath) throws Exception {
        int i;
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(filePath);
        LOGGER.info("Create Excel!");

        excelBeanConverterEngine.openFile(resourceAsStream);

        // Va chercher la liste des clubs dans la liste
        Collection<Club> clubList = excelBeanConverterEngine.getClubList();

        // Cree les clubs dans la base de donnees
        for (Club club : clubList) {
            clubService.create(club);
            LOGGER.info("create club " + club.getId() + " name " + club.getName());
        }

        // Va chercher la liste d'athlete dans la liste
        Collection<Athlete> athleteList = excelBeanConverterEngine.getAthleteList();

        // Cree les athletes dans la base de données
        for (Athlete athlete : athleteList) {
            athleteService.create(athlete);
        }

        Collection<Team> teamList;

        TeamType[] teamTypes = TeamType.values();
        for (TeamType teamType : teamTypes) {
            teamList = excelBeanConverterEngine.getTeamList(teamType);

            for (Team team : teamList) {
                LOGGER.info("create team " + team.getName());

                for (Athlete athlete : team.getAthletes()) {
                    LOGGER.info("athlete " + athlete.getName());
                }
                teamService.create(team);
            }
        }

    }
}
